package net.sxnic.jhitem.itemannex.action;

import java.io.File;
import java.io.FileInputStream;

import net.sxnic.comm.CommConstant;
import net.sxnic.comm.utils.CommUtils;
import net.sxnic.item.mdata.Mdata;
import net.sxnic.jhitem.itemannex.ItemAnnex;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description:  [一句话描述该类的功能]
 * @Author [姓名] [联系方式]
 * @CreateDate:
 * @UpdateDate:   
 * @Version 1.0
 */
 
public class Upload extends ItemAnnexAction  {
	private static final long serialVersionUID = 1L;

	private static Logger logger = LoggerFactory.getLogger(Upload.class);
	
	//附件最大为2MB
	private static final long MAXSIZE = 2097152L;
	//获取上传路径
	//private static String path = "/java/upload/";
	private static String path = getFileBasePath();
	//文件类别
	private String fileSort;
	private File uploadfile;
	
	private String uploadfileFileName;

	private String uploadfileContentType;

	private int pageid;
	
	private Mdata mdata;
	
	/**
	 * 从属性文件中读取附件保存的基本路径
	 * 
	 * @return 附件保存的基本路径
	 */
	public static String getFileBasePath() {
		String basePath = "";

		if (CommUtils.isWindowsOs()) {
			basePath = (String) CommConstant.PROPERTY_MAP.get("upload.file.path");
			if (basePath.startsWith("DIR:")) {
				basePath = StringUtils.remove(basePath, "DIR:");
			}

			if (!basePath.endsWith("\\")) {
				basePath = basePath + "\\";
			}

		} else {
			basePath = (String) CommConstant.PROPERTY_MAP.get("upload.file.path.linux");
			if (basePath.startsWith("DIR:")) {
				basePath = StringUtils.remove(basePath, "DIR:");
			}

			if (!basePath.endsWith("/")) {
				basePath = basePath + "/";
			}
		}

		return basePath;
	}
	
	public void prepare() throws Exception {
		if (StringUtils.isNotBlank(id)) {
			//获取上传附件
			annex001List = itemAnnexManager.findListByFileSort("001", id);
			annex002List = itemAnnexManager.findListByFileSort("002", id);
		}

	}

	public String execute() throws Exception {

		setJspPath(id);
		
		mdata = mdManager.get(id);

		// 验证主表数据是否存在
		if (mdata == null) {
			addActionMessage(getText("maindata.getContentsError"));
			return INPUT;
		}
		
		//上传文件
		if (uploadfile != null) {
			
			//附件文件大小判断
			if(getFileSizes(uploadfile)>MAXSIZE){
				addActionMessage("附件大小不能超过2M");
				return INPUT;
			}
			//设置上传文件的路径
			String realpath = path + mdata.getAppYear() + File.separator
					+ mdata.getCatalog1() + File.separator
					+ mdata.getCatalog2() + File.separator + id
					+ File.separator;
			//如果文件夹不存在，创建文件夹
			if (!(new File(realpath).exists())) {
				new File(realpath).mkdirs();
			}
			
			String filename = this.uploadfileFileName;
			String attachName = CommUtils.crtRandomUUID() + "."
					+ StringUtils.substringAfterLast(filename, ".");
			//如果文件存在，提示重新修改文件名
//			if ((new File(realpath+filename).exists())&&("001".equals(fileSort))) {
//				addActionMessage("服务端有重名的文件，请修改文件名重新上传");
//				return INPUT;
//			}
			
			String suffix = StringUtils.substringAfterLast(filename, ".");

			if("002".equals(fileSort)){
				//附件类型为001、002、003、004时，只可上传一个附件。
				//重复上传文件将会覆盖已上传的。
				if(annex002List.size()>0){
					ItemAnnex att = annex002List.get(0);
					//获取前面上传的文件
					File delFile = new File(att.getFilePath()+att.getFilePath());
					//删除已上传文件
					if(delFile.isFile())
						delFile.delete();
					//将文件拷贝到相应目录下
					FileUtils.copyFile(uploadfile, new File(realpath + attachName));
					att.setAttachName(attachName);
					att.setFileSize(String.valueOf(getFileSizes(uploadfile)));
					att.setFileName(filename);
					att.setFilePath(realpath);
					att.setDescription(itemAnnex.getDescription());
					att.setAttachOrder(itemAnnex.getAttachOrder());
					itemAnnexManager.update(att);
				}else{
					//将文件拷贝到相应目录下
					FileUtils.copyFile(uploadfile, new File(realpath + attachName));
					//保存附件数据
					saveAttachment(attachName, filename, itemAnnex.getDescription(), suffix, id, realpath, fileSort,String.valueOf(getFileSizes(uploadfile)), itemAnnex.getAttachOrder());
				}
				
			}else{
				//附件类型为001时，可上传多个附件。
				//将文件拷贝到相应目录下
				FileUtils.copyFile(uploadfile, new File(realpath + attachName));
				//保存附件数据
				saveAttachment(attachName, filename, itemAnnex.getDescription(), suffix, id, realpath, fileSort,String.valueOf(getFileSizes(uploadfile)), itemAnnex.getAttachOrder());
				
			}
			msg = "uploadSuccess";
		}
		
		if(pageid == 0){
			pageid = 1;
		}
		

		return SUCCESS;
	}
	
	private void saveAttachment(String attachName, String fileName,String description,
			 String fileType, String entityId, String filePath,String fileSort,String fileSize,Integer aOrder) {
		ItemAnnex itemAnnex = new ItemAnnex();
		if(aOrder == null){
			aOrder = 0;
		}
		itemAnnex.setAttachName(attachName);
		itemAnnex.setFileSize(fileSize);
		itemAnnex.setFilePath(filePath);
		itemAnnex.setFileName(fileName);
		itemAnnex.setDescription(description);
		itemAnnex.setFileType(fileType);
		itemAnnex.setBaseinfoId(entityId);
		itemAnnex.setFileSort(fileSort);
		itemAnnex.setAttachOrder(aOrder);
		try {
			itemAnnexManager.save(itemAnnex);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	/**
	 * 取得文件大小
	 * @param f
	 * @return
	 * @throws Exception
	 */
    public long getFileSizes(File f) throws Exception{
        long s=0;
        if (f.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(f);
           s= fis.available();
        } else {
            f.createNewFile();
            System.out.println("文件不存在");
        }
        return s;
    }

	public File getUploadfile() {
		return uploadfile;
	}

	public void setUploadfile(File uploadfile) {
		this.uploadfile = uploadfile;
	}

	public String getUploadfileFileName() {
		return uploadfileFileName;
	}

	public void setUploadfileFileName(String uploadfileFileName) {
		this.uploadfileFileName = uploadfileFileName;
	}

	public String getUploadfileContentType() {
		return uploadfileContentType;
	}

	public void setUploadfileContentType(String uploadfileContentType) {
		this.uploadfileContentType = uploadfileContentType;
	}

	public String getFileSort() {
		return fileSort;
	}

	public void setFileSort(String fileSort) {
		this.fileSort = fileSort;
	}
	
	public int getPageid() {
		return pageid;
	}

	public void setPageid(int pageid) {
		this.pageid = pageid;
	}
	
}
